package com.lb.jwitter.action.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;

import com.lb.jwitter.service.ConditionReport;
import com.lb.jwitter.service.TblDKMHLogMail;
import com.lb.jwitter.service.TblDKMHLogMailService;
import com.lb.jwitter.util.ApplicationContextProvider;
import com.lb.jwitter.util.ChumanoLogger;

public class AutoEmailTask {
	//private Log log = LogFactory.getLog(AutoEmailTask.class);
	private DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	private String mailSubject;

	public String getMailSubject() {
		return mailSubject;
	}

	public void setMailSubject(String mailSubject) {
		this.mailSubject = mailSubject;
	}

	private String mailFrom;

	public String getMailFrom() {
		return mailFrom;
	}

	public void setMailFrom(String mailFrom) {
		this.mailFrom = mailFrom;
	}
	
	private String mailCc;
	
	public String getMailCc() {
		return mailCc;
	}

	public void setMailCc(String mailCc) {
		this.mailCc = mailCc;
	}

	private String mailFromPersonal;

	public String getMailFromPersonal() {
		return mailFromPersonal;
	}

	public void setMailFromPersonal(String mailFromPersonal) {
		this.mailFromPersonal = mailFromPersonal;
	}

	private JavaMailSender mailSender;

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	private TblDKMHLogMailService tblDKMHLogMailService;

	public AutoEmailTask() {
		ApplicationContext context = ApplicationContextProvider
				.getApplicationContext();
		tblDKMHLogMailService = (TblDKMHLogMailService) context
				.getBean("tbl_DKMH_LogMailClient");
	}

	public void execute() {
		ChumanoLogger.init("Auto_email");
		try {			
			ChumanoLogger.log("Bat dau quet gui mail tu dong ");
			List<TblDKMHLogMail> tblDKMHLogMails = new ArrayList<TblDKMHLogMail>();
			
			List<ConditionReport> cons = new ArrayList<ConditionReport>();
			{
				ConditionReport con = new ConditionReport();
				con.setCol("tinhTrang");
				con.setValue1("DA_GUI");
				con.setOperator("ne");
				cons.add(con);
			}
			tblDKMHLogMails = tblDKMHLogMailService
					.findtblDKMHLogMailByCondition(cons, 0, 0);
			
			cons.clear();
			{
				ConditionReport con = new ConditionReport();
				con.setCol("tinhTrang");
				con.setOperator("isNull");
				cons.add(con);
			}
			List<TblDKMHLogMail> tblDKMHLogMails2 = tblDKMHLogMailService
			.findtblDKMHLogMailByCondition(cons, 0, 0);
			
			if(tblDKMHLogMails2 != null){
				tblDKMHLogMails.addAll(tblDKMHLogMails2);
			}
			
			String encodingOptions = "text/html; charset=UTF-8";

			GregorianCalendar c = new GregorianCalendar();
			
			XMLGregorianCalendar d;

			if (tblDKMHLogMails != null) {
				for (TblDKMHLogMail tblDKMHLogMail : tblDKMHLogMails) {
					try {
						if (tblDKMHLogMail.getHocVienId() != null
								&& tblDKMHLogMail.getHocVienId().getEmail() != null
								&& !tblDKMHLogMail.getHocVienId().getEmail()
										.isEmpty()) {
							MimeMessage msg = mailSender.createMimeMessage();
							msg.setHeader("Content-Type", encodingOptions);
							msg.setFrom(new InternetAddress(mailFrom,
									mailFromPersonal));
							msg.addRecipient(
									Message.RecipientType.TO,
									new InternetAddress(
											tblDKMHLogMail.getHocVienId()
													.getEmail(),
											(tblDKMHLogMail.getHocVienId()
													.getHoTen() != null ? tblDKMHLogMail
													.getHocVienId().getHoTen()
													: "")));
							msg.addRecipient(Message.RecipientType.CC, new InternetAddress(mailCc));
							DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
							String subj = "PDT-" + (tblDKMHLogMail.getDotDKId().getMa() == null ? "DKMH" : tblDKMHLogMail.getDotDKId().getMa()) + "-" + df.format(new Date());
							msg.setSubject(subj, "UTF-8");
							msg.setContent(tblDKMHLogMail.getNoiDung(),
									encodingOptions);

							mailSender.send(msg);

							c.setTime(new Date());
							d = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
							
							tblDKMHLogMail.setTinhTrang("DA_GUI");
							tblDKMHLogMail.setNgayGui(d);
							tblDKMHLogMailService
									.updatetblDKMHLogMail(tblDKMHLogMail);
							ChumanoLogger.log(dateFormat.format(new Date()) + ": Hoc vien " + tblDKMHLogMail.getHocVienId().getMSSV() + ": da gui");
							//System.out.println(tblDKMHLogMail.getHocVienId().getEmail() + "da gui");
						}
					} catch (Exception e) {
						tblDKMHLogMail.setTinhTrang("GUI_LOI");
						tblDKMHLogMailService
								.updatetblDKMHLogMail(tblDKMHLogMail);
						ChumanoLogger.log(dateFormat.format(new Date()) + ": Hoc vien " + tblDKMHLogMail.getHocVienId().getMSSV() + ": loi");
						ChumanoLogger.log("ERROR: " + e.getMessage());
						e.printStackTrace();						
					}

				}
			}
			ChumanoLogger.log(dateFormat.format(new Date()) + ": Ket thuc gui email tu dong: thanh cong");
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			ChumanoLogger.log(dateFormat.format(new Date()) + ": Ket thuc gui email tu dong: co loi trong qua trinh chay");
			ChumanoLogger.log("ERROR: " + e1.getMessage());
			e1.printStackTrace();
		} 
		ChumanoLogger.stop();
	}
}
